package com.skz;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    private static final int MAX_SEATS = 10;
    private static final int PEOPLES = 15;
    private static Semaphore semaphore = new Semaphore(MAX_SEATS);
    ExecutorService executorService = Executors.newFixedThreadPool(20);

    public static void main(String[] args) {
        new SemaphoreTest().test();
    }

    public void test() {
        for (int i = 0; i < PEOPLES; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "获得许可进入");
                    Thread.sleep(2000);
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "吃完走了。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }
}
